import React from 'react';
import {Spin, Card, Button, Row, Col, Table, Form} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, TABLE, DATE_FORMAT, FORM_ROW_OPTIONS} from '../constants';
import {signForApplyReport, getDetail} from './api';
import {injectIntl} from './intl';
import TextInput from 'Shared/components/TextInput';
import WrappedDatePicker from '../common/WrappedDatePicker';
import FileUpload from './FileUpload';
import styles from './style.css';
import Return from '../common/Return';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import {currency, partContractInvoiceStatus, transportType, declarePlace, declareType, packingType} from '../Enum';
import {newOrUpdateOrderValidator} from './validator';
const FormItem = Form.Item;
const EMPTY_ARRAY = [];

class SignForPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        data: {},
        packingListDetails: [],
        partOrderPIDetails: [],
    }
    componentDidMount() {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data,
                        packingListDetails: res.data.packingListDetails,
                        partOrderPIDetails: res.data.partOrderPIDetails,
                    });
                else
                    this.setState({loading: false});
            });
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    removeFilePath = file => {
        const data = this.state.data;
        const index = data.attachments.findIndex(item => item.fileId === file.fileId);
        if(index === -1)
            return null;
        const attachments = data.attachments || [];
        attachments.splice(index, 1);
        if(!this.state.hasOperat)
            this.setState({
                data: {
                    ...data,
                    attachments
                },
                hasOperat: true,
            });
    }
    onChangeUpload = value => {
        const data = this.state.data;
        const attachments = data.attachments || [];
        attachments.push(value[0]);
        if(!this.state.hasOperat)
            this.setState({
                data: {
                    ...data,
                    attachments
                },
                hasOperat: true,
            });
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const data = this.state.data;
        const isValid = newOrUpdateOrderValidator(data);
        if(!isValid) {
            this.setState({
                isValidate: true
            });
            return;
        }
        const condition = {
            receipterName: data.receipterName,
            receiptTime: data.receiptTime,
            attachments: data.attachments,
            rowVersion: data.rowVersion,
            signnedRemark: data.signnedRemark,
        };
        this.setState({loading: true});
        signForApplyReport(this.props.id, condition).then(res => {
            if(res.ok)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, packingListDetails, partOrderPIDetails, isValidate, loading} = this.state;
        const packingListColumns = [{
            title: formatMessage({
                id: 'signForPanel.column.packingListCode',
                defaultMessage: '箱单号'
            }),
            dataIndex: 'packingListCode',
        }, {
            title: formatMessage({
                id: 'signForPanel.column.packing',
                defaultMessage: '包装类型'
            }),
            dataIndex: 'packing',
            render: text => conventEnumValueToString(packingType, text)
        }, {
            title: formatMessage({
                id: 'signForPanel.column.container',
                defaultMessage: '包装规格'
            }),
            dataIndex: 'container',
        }, {
            title: formatMessage({
                id: 'signForPanel.column.length',
                defaultMessage: '长度'
            }),
            dataIndex: 'length',
        }, {
            title: formatMessage({
                id: 'signForPanel.column.width',
                defaultMessage: '宽度'
            }),
            dataIndex: 'width',
        }, {
            title: formatMessage({
                id: 'signForPanel.column.height',
                defaultMessage: '高度'
            }),
            dataIndex: 'height',
        }, {
            title: formatMessage({
                id: 'signForPanel.column.volume',
                defaultMessage: '体积'
            }),
            dataIndex: 'volume',
        }, {
            title: formatMessage({
                id: 'signForPanel.column.netWeight',
                defaultMessage: '净重'
            }),
            dataIndex: 'netWeight',
        }, {
            title: formatMessage({
                id: 'signForPanel.column.grossWeight',
                defaultMessage: '毛重'
            }),
            dataIndex: 'grossWeight',
        }];
        const partOrderPIColumns = [{
            title: formatMessage({
                id: 'signForPanel.column.partSaleOrderCode',
                defaultMessage: '销售订单编号'
            }),
            dataIndex: 'partSaleOrderCode',
        }, {
            title: formatMessage({
                id: 'signForPanel.column.partOrderPICode',
                defaultMessage: 'PI编号'
            }),
            dataIndex: 'partOrderPICode',
        }, {
            title: formatMessage({
                id: 'signForPanel.column.currency',
                defaultMessage: '币种'
            }),
            dataIndex: 'currency',
            render: text => conventEnumValueToString(currency, text)
        }, {
            title: formatMessage({
                id: 'signForPanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            dataIndex: 'partCode',
        }, {
            title: formatMessage({
                id: 'signForPanel.column.partName',
                defaultMessage: '备件名称'
            }),
            dataIndex: 'partName',
        }, {
            title: formatMessage({
                id: 'signForPanel.column.quantity',
                defaultMessage: '数量'
            }),
            dataIndex: 'quantity',
        }, {
            title: formatMessage({
                id: 'signForPanel.column.price',
                defaultMessage: '单价'
            }),
            dataIndex: 'price',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'signForPanel.column.totalAmount',
                defaultMessage: '金额'
            }),
            dataIndex: 'totalAmount',
            render: text => formatAmount(text)
        }];
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'signForPanel.column.common',
                        defaultMessage: '订单信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'signForPanel.operation.partInvoiceCode',
                                        defaultMessage: '发票编号'
                                    })}
                                    {...FORM_OPTIONS.item} >
                                        {data.partInvoiceCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'signForPanel.operation.invoiceAmount',
                                            defaultMessage: '发票金额'
                                        })} {...FORM_OPTIONS.item}>
                                        {formatAmount(data.invoiceAmount)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'signForPanel.operation.currency',
                                        defaultMessage: '币种'
                                    })}{...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(currency, data.currency)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'signForPanel.operation.status',
                                        defaultMessage: '发票状态'
                                    })}{...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(partContractInvoiceStatus, data.status)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'signForPanel.operation.invoicedDate',
                                        defaultMessage: '开票日期'
                                    })}{...FORM_OPTIONS.item}>
                                        {formatDateTime(data.invoicedDate, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'signForPanel.operation.partShipmentCode',
                                        defaultMessage: '发运单编号'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.partShipmentCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'signForPanel.operation.shipmentType',
                                        defaultMessage: '发运方式'
                                    })}{...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(transportType, data.shipmentType)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'signForPanel.operation.origin',
                                        defaultMessage: '起运地'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.origin}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'signForPanel.operation.destination',
                                        defaultMessage: '目的地'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.destination}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'signForPanel.operation.expectDepartedDate',
                                        defaultMessage: '预计离港日期'
                                    })}{...FORM_OPTIONS.item}>
                                        {formatDateTime(data.expectDepartedDate, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'signForPanel.operation.declarePlace',
                                        defaultMessage: '报关地点'
                                    })}{...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(declarePlace, data.declarePlace)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'signForPanel.operation.declareType',
                                        defaultMessage: '报关类型'
                                    })}{...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(declareType, data.declareType)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'signForPanel.operation.lcCode',
                                        defaultMessage: '信用证编号'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.lcCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'signForPanel.operation.receipterName',
                                        defaultMessage: '签收人姓名'
                                    })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.receipterName ? 'error' : null} required>
                                        <TextInput
                                            name="receipterName"
                                            value={data.receipterName}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'signForPanel.operation.receiptTime',
                                        defaultMessage: '签收时间'
                                    })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.receiptTime ? 'error' : null} required>
                                        <WrappedDatePicker
                                            name="receiptTime"
                                            value={data.receiptTime}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col {...FORM_ROW_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'signForPanel.operation.signnedRemark',
                                        defaultMessage: '签收备注'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        <TextInput
                                            type="textarea"
                                            name="signnedRemark"
                                            value={data.signnedRemark}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'signForPanel.operation.packingListDetails',
                            defaultMessage: '发运单箱单区域清单'
                        })}>
                        <Table
                            className="white-space-nowrap"
                            columns={packingListColumns}
                            rowKey="id"
                            pagination={false}
                            dataSource={packingListDetails}
                            {...TABLE} />
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'signForPanel.operation.partOrderPIDetails',
                            defaultMessage: '发运单备件区域清单'
                        })}>
                        <Table
                            className="white-space-nowrap"
                            columns={partOrderPIColumns}
                            rowKey="id"
                            pagination={false}
                            dataSource={partOrderPIDetails}
                            {...TABLE} />
                    </Card>
                    <Card title={formatMessage({
                        id: 'reportPanel.title.files',
                        defaultMessage: '附件清单'
                    })}>
                        <Row>
                            <Col {...FORM_OPTIONS.col}>
                                <FileUpload onChange={this.onChangeUpload}
                                    onRemove={this.removeFilePath}
                                    fileList={data.attachments || EMPTY_ARRAY}/>
                            </Col>
                        </Row>
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            loading={loading}>
                            {formatMessage({
                                id: 'signForPanel.operation.sava',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

SignForPanel.propTypes = {
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {
    tableSearch
} from './actions';
const mapDispatchToProps = (dispatch, props) => ({
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(null, mapDispatchToProps)(injectIntl(SignForPanel));
